package com.example.nasadailyimage;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	Handler handler;
	Bitmap image;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		handler = new Handler();
		refreshFromFeed();
	}

	private void refreshFromFeed() {
		final ProgressDialog dialog = ProgressDialog.show(this, "Loading",
				"Loading the image of the Day");

		Thread th = new Thread() {
			public void run() {

				final IotdHandler iotdHandler = new IotdHandler();
				iotdHandler.processFeed();
				image = iotdHandler.getImage();

				handler.post(

					new Runnable() {
						public void run() {
	
							resetDisplay(iotdHandler.getTitle(),
									iotdHandler.getDate(), iotdHandler.getImage(),
									iotdHandler.getDescription());
							dialog.dismiss();
						}
					}
				);
			}
		};

		th.start();

	}

	public void onRefresh(View view) {
		refreshFromFeed();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	private void resetDisplay(String title, String date, Bitmap image,
			StringBuffer description) {
		TextView titleView = (TextView) findViewById(R.id.imageTitle);
		titleView.setText(title);

		TextView dateView = (TextView) findViewById(R.id.imageDate);
		dateView.setText(date);

		ImageView imageView = (ImageView) findViewById(R.id.imageDisplay);
		imageView.setImageBitmap(image);

		TextView descriptionView = (TextView) findViewById(R.id.imageDescription);
		descriptionView.setText(description);

	}
	
	public void onSetWallPaper(View view)
	{
		Thread th = new Thread()
		{
			public void run()
			{
				WallpaperManager wallpaperManager = WallpaperManager.getInstance(MainActivity.this);
				
				try
				{
					wallpaperManager.setBitmap(image);
					handler.post(

					new Runnable() {
						public void run() {
							Toast.makeText(MainActivity.this, "Wall paper set",
									Toast.LENGTH_SHORT).show();
						}
					});
				}
				catch(Exception e)
				{
					e.printStackTrace();
					handler.post(

					new Runnable() {
						public void run() {
							Toast.makeText(MainActivity.this, "Error setting wallpaper",
									Toast.LENGTH_SHORT).show();
						}
					});
				}
			}
						
		};
		th.start();
		
	}
	
	
	
	

}
